package source.control;

import source.Enums.Side;
import source.control.Command;
import source.calcCmd.RobotCommand;
import source.control.CmdInterface;

public class Master implements Runnable{

	volatile public static int sleepfor;
	
	CmdInterface cmdInterface;
	
	
	public Master(CmdInterface m){
		cmdInterface = m;
	}
	
	@Override
	// run function for runnable interface
	public void run() {
		System.out.println("enter");
		int numberOfReady = 0;
		int numberOfCmd = 0;
		boolean pingReadyReceived = false;
		// initiate a ping to determine if uC is ready
		cmdInterface.getPort().write("ping");
		// the next command in line
		RobotCommand tmp = null;
		
		while(cmdInterface.isRunning()){
			cmdInterface.setWorking(true);
			cmdInterface.getPort().waitForReady();
			if (!pingReadyReceived){
				pingReadyReceived = true;
			} else {
				numberOfReady++;
			}
			// if the thread is stopped
			if (!cmdInterface.isRunning()) break;
			tmp = cmdInterface.readRow();
			
			if (tmp == null) { 
				sleepfor = 0;
				if (numberOfReady-1 == numberOfCmd || numberOfCmd == 0)
					break; 				
			} 
			if (tmp != null) sleepfor = tmp.getRealTime();
			if (cmdInterface.getPort().getOnline()) {
				if (tmp != null) {

					cmdInterface.getPort().write(tmp.toString());
					numberOfCmd++;
					
					//cmdInterface.setPrevSp(Side.LEFT, tmp.getSpeedL());
					//cmdInterface.setPrevSp(Side.RIGHT,tmp.getSpeedR());
				}
			} 
			tmp = null;
		}
		cmdInterface.done();

	}	
	
}
